package org.biouno.unochoice;

import com.alibaba.fastjson.JSONObject;
import hudson.Extension;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.model.Item;
import hudson.util.ListBoxModel;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import static hudson.Util.fixEmpty;
import static org.biouno.unochoice.util.Utils.getNodes;

@ExportedBean
public class DebConfig extends AbstractDescribableImpl<DebConfig> implements Serializable {

    //deb包名节点
    private String name;

    //第三方依赖,以，分隔
    private String thirdPartys;

    //内部依赖
    private List<DebList> depends;

    //打包路径
    private String debPaths;


    @DataBoundConstructor
    public DebConfig(String name, String thirdPartys, List<DebList> depends, String debPaths) {
        this.name = fixEmpty(name);
        this.thirdPartys = thirdPartys;
        this.depends = depends;
        this.debPaths = debPaths;
    }


    @Exported
    @Whitelisted
    public String getName() {
        return name;
    }

    @Exported
    @Whitelisted
    public List<DebList> getDepends() {
        return depends;
    }

    @Exported
    @Whitelisted
    public String getDebPaths() {
        return debPaths;
    }

    @Exported
    @Whitelisted
    public String getThirdPartys() {
        return thirdPartys;
    }


    @Override
    public String toString() {
        JSONObject jsonObject = new JSONObject();
        return jsonObject.toString();
    }

    public JSONObject toJSONObject() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", name);
        jsonObject.put("thirdPartys", thirdPartys);

        if (debPaths != null) {
            jsonObject.put("debPaths", debPaths.split(","));
        }
        List<JSONObject> depend = new ArrayList<>();
        if (depends!=null){
            depends.forEach(item->{
                depend.add(item.toJSONObject());
            });
        }
        jsonObject.put("depends", depend);
        return jsonObject;
    }

    private final static Pattern SCP_LIKE = Pattern.compile("(.*):(.*)");


    @Extension
    public static class DescriptorImpl extends Descriptor<DebConfig> {

        public ListBoxModel doFillNodeLabelItems(@AncestorInPath Item project) {

            ListBoxModel listBoxModel = new ListBoxModel();
            getNodes().forEach(node -> {
                listBoxModel.add(node);
            });
            return listBoxModel;
        }


        @Override
        public String getDisplayName() {
            return "";
        }
    }
}
